<template>
	<view class="zui-upload">
		<u-upload :fileList="fileList6" @afterRead="afterRead" @delete="deletePic" name="6" multiple :maxCount="1" width="180rpx" height="180rpx">
			<image :src="image" style="width: 180rpx;height: 180rpx;"></image>
		</u-upload>
	</view>
</template>

<script>
export default {
	name: 'zui-upload',
	props: {
		image: {
			type: [String, Number]
		}
	},
	data() {
		return {
			fileList6: [],
			token : uni.getStorageSync('token') || "",
		};
	},
	created() {},
	methods: {
		// 删除图片
		deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1);
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			lists.map(item => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url);
				
				let item = this[`fileList${event.name}`][fileListLen];
				this[`fileList${event.name}`].splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					})
				);
				fileListLen++;
			}
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: this.httpPath+'/app/tool/uploadImage', // 仅为示例，非真实的接口地址
					filePath: url,
					name: 'image',
					header: {
						'Authorization': "Bearer " + this.token,
					},
					success: res => {
						let data=JSON.parse(res.data)
						uni.$emit('upimg',data)
						setTimeout(() => {
							resolve(data.data);
						}, 1000);
					}
				});
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.both_ends {
	display: flex;
	justify-content: space-between;
	color: #9d97a7;
	font-size: 26rpx;
}
</style>
